#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动1688商品搜索系统
同时启动后端API服务和前端静态文件服务
"""

import os
import sys
import subprocess
import threading
import time
from http.server import HTTPServer, SimpleHTTPRequestHandler
import webbrowser

def start_api_server():
    """启动FastAPI后端服务"""
    print("启动后端API服务...")
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    subprocess.run([sys.executable, "-m", "uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"])

def start_frontend_server():
    """启动前端静态文件服务"""
    print("启动前端服务...")
    
    class CORSHTTPRequestHandler(SimpleHTTPRequestHandler):
        def end_headers(self):
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            super().end_headers()
        
        def do_OPTIONS(self):
            self.send_response(200)
            self.end_headers()
    
    # 切换到frontend目录
    frontend_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'frontend')
    os.chdir(frontend_dir)
    
    # 启动HTTP服务器
    server = HTTPServer(('localhost', 3000), CORSHTTPRequestHandler)
    print("前端服务启动在: http://localhost:3000")
    server.serve_forever()

def main():
    print("=" * 50)
    print("1688商品搜索系统启动中...")
    print("=" * 50)
    
    # 检查依赖
    try:
        import uvicorn
        import fastapi
    except ImportError:
        print("错误: 缺少必要的依赖包")
        print("请运行: pip install fastapi uvicorn")
        return
    
    # 启动后端服务（在新线程中）
    api_thread = threading.Thread(target=start_api_server, daemon=True)
    api_thread.start()
    
    # 等待后端服务启动
    print("等待后端服务启动...")
    time.sleep(3)
    
    # 启动前端服务（在新线程中）
    frontend_thread = threading.Thread(target=start_frontend_server, daemon=True)
    frontend_thread.start()
    
    # 等待前端服务启动
    time.sleep(2)
    
    # 自动打开浏览器
    print("\n" + "=" * 50)
    print("系统启动完成!")
    print("后端API: http://localhost:8000")
    print("前端界面: http://localhost:3000")
    print("=" * 50)
    print("\n正在打开浏览器...")
    
    try:
        webbrowser.open('http://localhost:3000')
    except:
        print("无法自动打开浏览器，请手动访问: http://localhost:3000")
    
    print("\n按 Ctrl+C 停止服务")
    
    try:
        # 保持主线程运行
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n正在停止服务...")
        print("服务已停止")

if __name__ == "__main__":
    main()